package com.service;

import com.bean.CrowdData;
import com.util.SqliteHelper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther 烁烁
 * @date 2019/9/19 10:38
 */

public class CrowdService {
    public static Boolean save(CrowdData crowdData) {
        try {
            SqliteHelper h = new SqliteHelper();
            if(getCrowdList(crowdData).size()==0){
                h.executeUpdate("INSERT INTO `wechat_crowd` VALUES('" + crowdData.getWechatName() + "','" + crowdData.getCrowdNumber() + "','" + crowdData.getTime()+"');");
            }else{
                h.executeUpdate("UPDATE `wechat_crowd` SET crowd_number='" + crowdData.getCrowdNumber()+"' WHERE wechat_name='" + crowdData.getWechatName() + "' AND time='" + crowdData.getTime() + "';");
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

        /**
         * 按条件查询或者查询全部
         * @param cd 不必须,传入则按条件查询
         * @return
         */
        public static List<CrowdData> getCrowdList(CrowdData cd) {
            List<CrowdData> rsList = new ArrayList<CrowdData>();
            try {
                SqliteHelper h = new SqliteHelper();
                String sql = "SELECT * FROM `wechat_crowd`";
                if (cd != null) sql += (" WHERE wechat_name=? AND time=?");
                PreparedStatement preState = h.getCon().prepareStatement(sql);
                if (cd != null) preState.setString(1, cd.getWechatName());
                if (cd != null) preState.setString(2, cd.getTime());
                ResultSet rs = preState.executeQuery();
                while (rs.next()) {
                    CrowdData crowdData = new CrowdData(
                            rs.getString("wechat_name"),
                            rs.getString("crowd_number"),
                            rs.getString("time"));
                    rsList.add(crowdData);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return rsList;
        }
    }
